import React, { Component, Fragment } from "react";
import { PlusOutlined } from "@ant-design/icons";
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input, DatePicker,
    Select, Popconfirm, message, Collapse, Alert, TreeSelect, TimePicker, Tree,
    AutoComplete, Tabs, Col, Row, Dropdown, Card, Pagination, Spin, Skeleton, Progress,
    Drawer, Tag, Badge, Radio, Steps, Transfer, notification, Empty, Calendar, Checkbox, Upload, List, Avatar
} from "antd";
import { iconFontUrl, zhizhouitemUploadTemplateUrl, zhizhouClassNameUploadTemplateUrl, inspectitemUploadTemplateUrl } from "../js/config.js";
//import echarts from 'echarts';
import { getEpidemicThemeByDepartmentApi, deleteThemeApi, releaseEpidemicThemeApi, stopThemeApi, queryRecordByFormKeyApi, getStatisticalAnswerAPi, getReleaseEpidemicThemeNumApi, queryItemsApi } from "../js/api"
import * as echarts from 'echarts';
import { exportExcel } from "../js/utils.js";
import moment from "moment";
import { addRelationApi, getRelationtApi, getSelectTitleByDepartmentApi } from "../js/api.js";
const { TreeNode } = Tree;
const RangePicker = DatePicker.RangePicker;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});
// const echarts = require('echarts');

const { Step } = Steps;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Option = Select.Option;

const success = () => {
    message.success({
        content: '操作成功',
        className: 'custom-class',
        style: {
            marginTop: '48vh',
        },
    });
};
const fail = () => {
    message.success({
        content: '操作失败',
        className: 'custom-class',
        style: {
            marginTop: '48vh',
        },
    });
};
class EpidemicContent extends Component{
    constructor(props) {
        super(props);
        this.state = {
            addUserVisible: false, //控制新增用户模态框显示隐藏
            updateUserVisible: false, //控制修改用户信息模态框显示隐藏
            alertVisible: false, //提示用户名已存在
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            identityFilter: [],
            columnData: [],
            filteredInfo: null,
            sortedInfo: null,
            exportUserInfoVisible: false,
            item: '',
            addVisible: false,
            fileList: [],
            uploading: false,
            detailVisible: false,
            detailExist: false,
            DrawerIsuse:undefined
        };
    }

    componentDidMount() {
        this.refreshData();
    }
   
    

    
    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getSelectTitleByDepartmentApi(sessionStorage.getItem("departmentId"))
        .then((res)=>{
            res.data.data.titleList.forEach((item, index)=>{
                columnData.push({
                    key: index + 1,
                    item: item.title,
                });
            });
            this.setState({
                columnData: columnData,
                tableLoading: false
            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    

    }

    showDetailDrawer(e){
        console.log("swsd")
        this.setState({
            detailExist: true,
            detailVisible: true
           
        })
      
    }
    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false
            
        })
    }
    

    
    



    render() {
        
       
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "打卡内容",
                dataIndex: "item",
                key: "item"
            }
            // ,
            // {
            //     title: "操作详情",
            //     key: "action",
            //     render: (text, record) => (
            //         <span>
            //             <a href="javascript:;" onClick={() => this.updateHandleClick(record.item)}>修改</a>
            //             <Divider type="vertical" />

            //             <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
            //                 onConfirm={() => this.handleDelete(record.item)}>
            //                 <a href="#">删除</a>
            //             </Popconfirm>
            //         </span>
            //     )
            // }
        ]



        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                <Button type="primary" size="large" onClick={this.showDetailDrawer.bind(this)}
                    >打卡内容配置</Button>  
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    //onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
                    {
                    this.state.detailExist ? (
                        <EpidemicContentDetail
                            visible={this.state.detailVisible}
                            
                            that={this} />
                    ) : null
                }
            </div>
        )
    }
    
}

class EpidemicContentDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            DrawerIsuse:props.DrawerIsuse,
            themeId:props.themeId,
            that: props.that,
            treeData: [],
            checkedKeys: [],
            selectAll: [],
            confirmLoading: false,
            expandedKeys: [],
            msg: "", //提交失败时的提示语
            selectedKeys: [],
            autoExpandParent: true,
            
        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        this.refreshData();
        
       
    
        
    }



    componentWillReceiveProps(props) {
        

        this.setState({
            
            visible: props.visible,
            
            that: props.that,
            
            
        });
        
    }

    refreshData() {
       
        this.setState({
            confirmLoading: true,
        })
        getRelationtApi(sessionStorage.getItem("departmentId"))
        .then((res)=>{
             let treeData = [];
            let checkedKeys = [];
            let selectAll = [];
            res.data.data.forEach((value, i)=>{
                let item={
                    title: value.title,
                    key: value.contentId
                }
                treeData.push(item);
                if(value.isUse==1){
                    checkedKeys.push(value.contentId)
                }
                selectAll.push(value.contentId)
            })
            this.setState({
                treeData: treeData,
                confirmLoading: false,
                selectAll: selectAll,
                checkedKeys: checkedKeys,

            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
            
           
    }

    onChange = (e) => {


        if (e.target.checked) {

            this.setState({
                checkedKeys: this.state.selectAll

            })

        }


        else {


            this.setState({
                checkedKeys: []

            })


        }

    }
    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
        console.log("checkedKeys" + checkedKeys)
    }

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
    }
    handleUpdateClick(){
        this.setState({
            confirmLoading: true
        });
                console.log("====", this.state.checkedKeys)
                let Info=[];
                this.state.checkedKeys.forEach((item, index)=>{
                  Info.push({
                      "titleId":item,
                      "departmentId":sessionStorage.getItem("departmentId")
                  })
                    
                    }
                   
                )
                console.log(Info);
                addRelationApi(Info)
                .then((res)=>{
                    if (res.data.code == 1000) {
                        message.success("更新成功!");
                        this.setState({
                            confirmLoading: false
                        });
                        this.state.that.handleDetailDrawerCancel();
                        this.state.that.refreshData();
                    } else if (res.data.code == 2000) {
                        this.setState({
                            alertVisible: true,
                            confirmLoading: false,
                            msg: "修改失败,请检查信息或稍后再试!"
                        });
                    }
                })
              
    }


    //修改巡查内容
    // handleUpdateClick() {
    //     this.setState({
    //         confirmLoading: true
    //     });
    //     console.log("====", this.state.checkedKeys)
    //     addContentItemApi(parseInt(this.state.themeId), this.state.checkedKeys)
    //     .then((res)=>{
    //         if (res.data == "success") {
    //             message.success("更新成功!");
    //             this.setState({
    //                 confirmLoading: false
    //             });
    //             this.state.that.handleDetailDrawerCancel();
    //             this.state.that.refreshData();
    //         } else if (res.data == "fail") {
    //             this.setState({
    //                 alertVisible: true,
    //                 confirmLoading: false,
    //                 msg: "修改失败,请检查信息或稍后再试!"
    //             });
    //         }
    //     })
    // }
    
   
   
    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            let color = { color: "#000000" };
            if (item.schoolId != undefined) {
                if (item.schoolId == 0) { color = { color: "#000000" } }
                else if (item.schoolId != 0) { color = { color: "#FF9966" } }
            }
            if (item)
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
        }
        return <TreeNode {...item} />;
    })

    render() {
        

        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

       

       

        

        return (
            <div>

                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={1100}
                    title='打卡内容'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Skeleton loading={this.state.confirmLoading} active>
                    <Checkbox onChange={this.onChange}  checked={this.state.checkedKeys.length == this.state.treeData.length ? true : false}>全部</Checkbox>
                    <div>
                        
                        <Tree
                        checkable
                        
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                        
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                        
                    
                    </div>
                    
                    {/* {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    } */}
                </Skeleton>

                    {this.state.DrawerIsuse==1 ?
                    (<div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>)
                    :
                    (<div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Row type="flex" justify="space-around" align="middle">
                            {/* <Col span={18}>
                                <Alert style={{ textAlign: "left" }} message="打勾表示已为巡查任务配置该项，再次点击复选框决定本次是否配置该项。" type="info" showIcon />
                            </Col> */}
                            <Col span={21}>
                                <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)} >关闭</Button>
                            </Col>
                            <Col span={3}>
                                <Button type="primary" size="large" loading={this.state.confirmLoading}
                                    onClick={this.handleUpdateClick.bind(this)} >保存</Button>
                            </Col>
                        </Row>
    
                    </div>)
                }


                    
                </Drawer>
                
            </div>

        );
    }
}


class EpidemicForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            formlist: [],
            tableloading: true,
            confirmLoading: false,   //发布loading
            drawerOpen: false,  //统计界面
            itemsRecord: [],  //表单项统计
            formKey: "",
            startTime: "",
            endTime: ""
        }
    }

    componentDidMount() {
        this.refreshData();
    }
    //获取学校所有打卡
    refreshData = () => {
        const schoolId = sessionStorage.getItem("departmentId");
        getEpidemicThemeByDepartmentApi(schoolId)
            .then(res => {
                this.setState({
                    formlist: res.data.reverse(),
                    tableloading: false
                })
            })
    }
    //删除表单
    deleteTheme = (formKey) => {
        this.setState({ tableloading: true })
        deleteThemeApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    message.success("删除成功");
                    this.refreshData(); //删除后重新获取学校表单，更新列表
                }
                else {
                    message.error("删除失败")
                    this.setState({ tableloading: false })
                }
            })
    }
    //发布表单
    async releaseEpidemicTheme(formKey, displayType){
        let flag = true
        await getReleaseEpidemicThemeNumApi(sessionStorage.getItem("departmentId"), displayType).then(res => {
            if (res.data.data == "无法发布") {
                flag = false
                if (displayType == 1)
                    notification.info({
                        message: "小程序端已有表单正在发布中，请先停止"
                    })
            }
            else
                this.setState({
                    open: true
                });
        })

        if (formKey && flag) {
            this.setState({
                tableloading: true,
                confirmLoading: true
            })
            releaseEpidemicThemeApi(formKey).then(res => {
                if (res.data.msg == "success") {
                    message.success("发布成功");
                    this.setState({
                        confirmLoading: false,
                        open: false,
                    })
                    this.refreshData(); //发布后重新获取学校表单，更新列表
                }
                else {
                    this.setState({
                        confirmLoading: false,
                        tableloading: false
                    })
                    message.error("发布失败")
                }

            })
        }
        else
            message.warning("发布失败")

    }
    //停止发布
    stopTheme = (formKey) => {
        this.setState({ tableloading: true })
        stopThemeApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    message.success("中止成功");
                    this.refreshData(); //停止发布后重新获取学校表单，更新列表
                }
                else {
                    message.error("中止失败")
                    this.setState({ tableloading: false })
                }
            })
    }

    //选项统计
    record = (formKey) => {
        getStatisticalAnswerAPi(formKey).then(res => {
            console.log(res);
            //设置题目选择数量占比
            res.data.forEach((item, index) => {
                if (item.options) {
                    let allnum = 0;
                    item.options.forEach(option => {
                        allnum += option.num
                    })
                    item.options.forEach((option, i) => {
                        if (allnum == 0)
                            res.data[index].options[i].percent = 0
                        else
                            res.data[index].options[i].percent = (option.num / allnum * 100).toFixed(0)//保留整数
                    })
                }
            })
            this.setState({
                drawerOpen: true,
                itemsRecord: res.data.filter(item => item.options)  //暂时只统计选择 不统计文本
            })
        })
    }
    //关闭统计回调
    onCloseDrawer = () => {
        this.setState({
            drawerOpen: false
        })
    }

    //以下日期api为限制表单有效期配置
    range = (start, end) => {
        const result = []
        for (let i = start; i < end; i++) {
            result.push(i)
        }
        return result
    }
    // 日期禁用
    disabledDate = (current) => {
        // return current && current < moment().subtract(1, 'days')
        return current && current < moment().subtract(1, 'days').endOf('day')
        // return current && current < moment().endOf('day')
    }
    
    //关闭显示发布时间设定框
    handleCancel = () => {
        this.setState({
            open: false,
            formKey: "",
            confirmLoading: false,
            tableloading: false
        })
    };

    //导出提交记录
    async exportSubmissionRecord(formKey, contentType) {
        // Excel标题
        let header = []
        let outerData = []
        await queryItemsApi(formKey)
            .then(res => {
                if (res.data.msg == "success") {
                    header.push({
                        title: "用户id",
                        dataIndex: "userId",
                        key: "userId"
                    });
                    header.push({
                        title: "用户名",
                        dataIndex: "userName",
                        key: "userName"
                    });
                    header.push({
                        title: "提交时间",
                        dataIndex: "modifyTime",
                        key: "modifyTime"
                    });
                    if (contentType == 2) {
                        header.push({
                            title: "分数",
                            dataIndex: "score",
                            key: "score"
                        });
                    }
                    res.data.data.forEach((item, index) => {
                        header.push({
                            title: item.formItemProps.label,
                            dataIndex: item.formItemProps.name,
                            key: item.formItemProps.name
                        });
                    })

                    if(contentType === 2)
                    {
                        let answer = {}
                        answer["userId"] = "考试答案"
                        answer["userName"] = ""
                        answer["modifyTime"] = ""
                        answer["score"] = ""
                        res.data.data.forEach((item, index) => {
                            //判断这是否是考试题
                            if(item.formItemProps.hasOwnProperty("answer"))
                            {
                                answer[header[index+4].key] = ""
                                //单选题
                                if(item.type === "radio")
                                {
                                    let max = 0//寻找最佳答案（因为有可能有次优解）
                                    for(let i=0;i<item.formItemProps.answer.length;i++)
                                    {
                                        if(item.formItemProps.answer[i].score>0 && item.formItemProps.answer[i].score>item.formItemProps.answer[max].score)
                                        {
                                            max = i;
                                        }
                                    }
                                    answer[header[index+4].key] = item.formItemProps.answer[max].value
                                }
                                //多选题
                                else if(item.type === "checkbox")
                                {
                                    for(let i=0;i<item.formItemProps.answer.length;i++)
                                    {
                                        if(item.formItemProps.answer[i].score>0)
                                        {
                                            answer[header[index+4].key] = answer[header[index+4].key]+item.formItemProps.answer[i].value+","
                                        }
                                    }
                                }
                            }
                            else
                            {
                                answer[header[index+4].key] = ""
                            }
                        });
                        outerData.push(answer);
                    }
                }
            })

        await queryRecordByFormKeyApi(formKey)
            .then(res => {
                if (contentType !== 1) {
                    res.data.forEach((item, index) => {
                        let temp = {}
                        temp["userId"] = item.userId
                        temp["userName"] = item.userName
                        temp["modifyTime"] = item.modifyTime
                        for (let i = 3; i < header.length; i++) {
                            temp[header[i].key] = item.data[i - 3].content;
                        }
                        outerData.push(temp);
                    });
                }
                else if (contentType === 2) {
                    res.data.forEach((item, index) => {
                        let temp = {}
                        temp["userId"] = item.userId
                        temp["userName"] = item.userName
                        temp["modifyTime"] = item.modifyTime
                        temp["score"] = item.score
                        for (let i = 4; i < header.length; i++) {
                            temp[header[i].key] = item.data[i - 4].content;
                        }
                        outerData.push(temp);
                    });
                }
            })
        if (outerData.length == 0) {
            message.warning("目前没有提交数据")
        }
        else {
            exportExcel(header, outerData, "提交记录.xlsx")
        }
    }

    toCreateForm = () => {
        const schoolId = sessionStorage.getItem("departmentId")
        //window.location.href = "http://localhost:3001/createEpidemic?schoolId=" + schoolId
        window.location.href = "http://47.111.158.147:3001/createEpidemic?schoolId=" + schoolId
    }

    render() {
        //table列配置
        const columns = [
            {
                title: '表单名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                //status 0:未发布 1:发布中 2:停止发布
                //筛选配置
                filters: [
                    {
                        text: "未发布",
                        value: 0
                    },
                    {
                        text: "发布中",
                        value: 1
                    },
                    {
                        text: "已停止",
                        value: 2
                    }
                ],
                //筛选
                onFilter: (value, record) => record.status == value,
                render: (status) => {
                    return (
                        <Tag color={
                            (() => {
                                switch (status) {
                                    case 1:
                                        return "#2db7f5"
                                    case 0:
                                        return "blue"
                                    case 2:
                                        return "silver"
                                    default:
                                        return null;
                                }
                            })()}>
                            {
                                (() => {
                                    switch (status) {
                                        case 1:
                                            return "发布中"
                                        case 0:
                                            return "未发布"
                                        case 2:
                                            return "已停止"
                                        default:
                                            return null;
                                    }
                                })()
                            }</Tag>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                render: (text, record) => {
                    return (
                        <Fragment>
                            {/* <a href={`http://localhost:3001/detail?schoolId=${record.departmentId}&formkey=${record.formKey}`}> */}
                            <a href={`http://47.111.158.147:3001/detail?schoolId=${record.departmentId}&formkey=${record.formKey}`}>
                                查看
                            </a>
                            <Divider type="vertical" />
                            {(() => {
                                switch (record.status) {
                                    case 1:
                                        return (
                                            <Fragment>
                                                <Popconfirm title="您确定要停止此表单的发布吗" onConfirm={() => { this.stopTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>停止发布</a>
                                                </Popconfirm>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.record(record.formKey)} >统计</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.exportSubmissionRecord(record.formKey, record.contentType)} >导出提交记录</a>
                                            </Fragment>
                                        )
                                    case 0:
                                        return (
                                            <Fragment>
                                                <a onClick={() => this.releaseEpidemicTheme(record.formKey, record.displayType)} >发布</a>
                                                <Divider type="vertical" />
                                                {/* <a href={`http://localhost:3001/update?schoolId=${record.departmentId}&formkey=${record.formKey}`}> */}
                                                <a href={`http://47.111.158.147:3001/update?schoolId=${record.departmentId}&formkey=${record.formKey}`}>
                                                    更新
                                                </a>
                                                <Divider type="vertical" />
                                                <Popconfirm title="您确定删除吗" onConfirm={() => { this.deleteTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>删除</a>
                                                </Popconfirm>
                                            </Fragment>)
                                    case 2:
                                        return (
                                            <Fragment>
                                                <a onClick={() => this.releaseEpidemicTheme(record.formKey, record.displayType)} >重新发布</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.record(record.formKey)} >统计</a>
                                                <Divider type="vertical" />
                                                <a onClick={() => this.exportSubmissionRecord(record.formKey, record.contentType)} >导出提交记录</a>
                                                <Divider type="vertical" />
                                                <Popconfirm title="您确定删除吗" onConfirm={() => { this.deleteTheme(record.formKey) }} okText="确定" cancelText="取消">
                                                    <a>删除</a>
                                                </Popconfirm>
                                            </Fragment>
                                        )
                                    default:
                                        return null;
                                }
                            })()}
                        </Fragment>
                    )
                }
            }
        ];
        return (
            <div>
                {/*选项统计 */}
                <Drawer
                    visible={this.state.drawerOpen}
                    closable={false}
                    onClose={this.onCloseDrawer}
                    width="35vw"
                >
                    {this.state.itemsRecord.map((itemRecord, index) =>
                        <ItemRecord
                            itemRecord={itemRecord}
                        >
                        </ItemRecord>
                    )}
                </Drawer>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" size="large" onClick={this.toCreateForm}>
                        <PlusOutlined />创建表单
                    </Button>
                </div>
                <Table
                    dataSource={this.state.formlist}    //数据源
                    columns={columns}   //列配置
                    locale={{ emptyText: '暂无数据' }}
                    loading={this.state.tableloading}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showQuickJumper: true,
                        showSizeChanger: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                    //额外展开行 内嵌子表格
                    expandedRowRender={(record) => {
                        return (
                            <div >
                                <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                    <Badge status="processing" text="表单描述" />
                                    <div style={{ paddingLeft: 15, paddingTop: 5 }}>
                                        {record.description ? record.description : "无"}
                                    </div>
                                </p>
                                {/* 表单填写途径为微信端网页时显示链接 */}
                                {record.displayType == 2 ?
                                    <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                        <Badge status="processing" text="网页链接" />
                                        <div style={{ paddingLeft: 15, paddingTop: 5 }}>
                                            <div style={{ display: "flex" }}>
                                                <Input id="linkAddress" ref={this.input} value={record.linkAddress} readOnly style={{ padding: 0, color: "gray", whiteSpace: "nowrap", textOverflow: "ellipsis", overflow: "hidden", width: "34vw", border: "none", backgroundColor: "#fafafa" }}></Input>
                                                <Button style={{ padding: "4.5px 0" }} size="small" type="link" onClick={() => { this.input.current.select(); document.execCommand('copy'); message.success("复制成功") }}>复制</Button>
                                            </div>
                                        </div>
                                    </p> : null}
                                <p style={{ margin: "0, 0, 5px, 0 ", color: "gray" }}>
                                    <Badge status="processing" text="发布时间" />
                                    <div style={{ paddingLeft: 15, paddingTop: 5, paddingBottom: 5 }}>
                                        {record.status !== 0 ? moment(record.startTime).format('YYYY-MM-DD HH:mm:ss') + " -- " + moment(record.endTime).format('YYYY-MM-DD HH:mm:ss') : " 未发布"}
                                    </div>
                                </p>
                            </div>
                        )
                    }
                    }
                    //不加的话table会认错
                    rowKey="formKey"
                />
            </div >
        )
    }
}

//表单选项统计组件
class ItemRecord extends Component {
    constructor() {
        super()
    }
    render() {
        const itemRecordColumns = [
            {
                title: "选项",
                dataIndex: "label",
                key: "label",
                width: "12vw",
            },
            {
                title: "小计",
                dataIndex: "num",
                key: "num",
                width: "6vw",
                sorter: (a, b) => a.num - b.num,
            },
            {
                title: "比例",
                dataIndex: "percent",
                key: "percent",
                sorter: (a, b) => a.num - b.num,
                render: (percent) => (
                    <Progress percent={percent}
                        status="active"
                    ></Progress>
                )
            }
        ]
        return (
            <Fragment>
                <div style={{ margin: "12px 0" }}>
                    <Badge status="processing" />
                    <span style={{ color: "gray" }}>题目:</span>
                    <span style={{ color: "#66b1ff", marginRight: "4px" }}>{this.props.itemRecord.label}</span>
                    <span style={{ color: "silver" }}>{this.props.itemRecord.type == "radio" ? "[单选题]" : "[多选题]"}</span>
                </div>
                <Table
                    dataSource={this.props.itemRecord.options}    //数据源
                    columns={itemRecordColumns}   //列配置
                    pagination={{ hideOnSinglePage: true }} //单页不显示页码
                />
                <div style={{ height: "2vh" }}></div>
            </Fragment>
        )
    }
}

export{EpidemicForm}

export{EpidemicContent}